// 需在wxml 必须定义 name='code' data-name='code' data-validator='required,code'或者 data-validator='ignore,code' 
// 非必须定义 data-errorMsg
// 返回的错误信息在$invalidMsg里 如果$invalidMsg 为 true则可以提交表单
// data里自定义验证规则 格式[{ code: new RegExp(res.data.data), msg: "验证码有误！" }]
class wxValidate {
  constructor(e, context) {
    this.init();
  };
  init(e, context) {
    this.initData();
    this.initDefaultRule();
  }
  initData() {
    this.form = {};
    this.errorList = []
  }
  initDefaultRule() {
    // 定义验证规则 
    this.rules = {
      required: { rule: /.+/, msg: '该选项为必填项，请输入' },
      phone: { rule: /^1[34578][0-9]{9}$/, msg: '手机号格式不正确' },
      password: { rule: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,10}$/, msg: '请输入6-10位密码,字母加数字' },
      code: { rule: /^\d{6}$/, msg: '验证码格式不正确' },
      minLength: { rule(val) { return val != "" && val.length > 4 ? false : true }, msg: '长度超出限制' },
      same: { rule(val) { return val && val === this.data.password }, msg:"确认密码错误"}
    }
  }
  // 增加验证规则 
  addRule(newRule) {
    newRule.forEach(item => {
      for (var key in item) {
        key === 'msg' ? '' : this.rules[key] = { rule: item[key], msg: item['msg'] }
      }
    })
  }
  // 验证规则是否存在
  checkRule (rule) {
    return this.rules.hasOwnProperty(rule) && rule in this.rules
  }
  // 失去焦点 验证
  validate(e, context) {
    let form = context.data.form || this.form;
    let value = (e.detail.value || '').trim();
    let validator = e.currentTarget.dataset.validator ? e.currentTarget.dataset.validator.split(',') : [];
    // wxml 定义错误规则
    let errorMsg = e.currentTarget.dataset.errormsg
    // 是否必填
    let isRequired = validator[0].split('=')[0]
    let ruleName = validator[1].split('=')[0]
    let rule = this.checkRule(ruleName)?this.rules[ruleName].rule || /.*/:false;
    let requiredRule = isRequired === 'required' ? true : false;
    let name = e.currentTarget.dataset.name
    let nameMsg = name + 'Msg'
    this.errorList = [];
    // 规则是函数
    if (!rule) {console.error(`没有( ${ruleName} )的检测方法`);return false;}
    else if ('function' === typeof rule) {
      form[ruleName] = rule.call(context, value) ? true : this.rules[ruleName].msg
    }
    else {
      // 必填项检测
      if (requiredRule) {
        let ruquiredFlag = this.rules['required'].rule.test(value) ? true : false;
        this.rules[ruleName].msg = errorMsg ? errorMsg : this.rules[ruleName].msg;
        ruquiredFlag ? form[ruleName] = rule.test(value) ? true : this.rules[ruleName].msg : form[ruleName] = this.rules['required'].msg
      }
      // 非必填项检测
      else {
        value ? form[ruleName] = rule.test(value) ? true : this.rules[ruleName].msg : form[ruleName] = true
      }
    }
    // 错误提示信息
    form['$invalidMsg'] = form[ruleName]
    form['$invalidMsg'] === true ? context.setData({ [nameMsg]: false }) : context.setData({ [nameMsg]: true })
    context.setData({
      form: form
    })
  }
  // 必填项验证 用户直接提交表单的验证
  checkRequired(e, context, properites) {
    let form = context.data.form || this.form;
    this.errorList = [];
    properites.forEach(item => {
      if (!this.rules['required'].rule.test(e.detail.value[item])) {
        this.rules[item].msg = context.data.errorList && context.data.errorList[item] ? context.data.errorList[item] : this.rules[item].msg
        form[item] = this.rules[item].msg
      }
    })
    for (var key in form) {
      if (key !== '$invalidMsg' && form[key] != true) {
        this.errorList.push(form[key])
        form['$invalidMsg'] = this.errorList[0] || true
      }
    }
    for (var key in form) {
      let newKey = key + "Msg"
      if (form[key] != true && key != '$invalidMsg') {
        context.setData({ [newKey]: true })
      }else{
        context.setData({ [newKey]: false })
      }
    }
    context.setData({
      form: form
    })
  }
}
export default wxValidate
